'use strict';

const authenticatorService = require('../../context/authenticator/services');

function identificationMiddlewareBuilder(opt) {
  return async(req, res, next) => {
    console.log('user identity validated');
    const { cookies } = req;
    if (!cookies || !cookies['builder-token']) {
      const { code = '' } = req.query;
      const { uid = '', upass = '' } = req.body;
      // identification
      const authResult = await authenticatorService.checkIdentity({
        userId: `${uid}`,
        userCode: `${code}`,
        userPassword: `${upass}`,
      });
      if (authResult.success) {
        res.cookie(authResult.authKey, authResult.authToken);
      }
    }
    const checkResult = await authenticatorService.checkCookie(cookies);
    if (!checkResult) {
      return res.status(401).message({
        errcode: -1,
        message: 'authenticate fail',
      });
    } else if (checkResult.refresh) {
      res.cookie(authResult.authKey, authResult.authToken);
    }
    return next();
  };
}

Object.assign(module.exports, {
  identificationMiddlewareBuilder,
});
